#include "ball.h"
#include <QPainter>
#include <QBrush>
#include <QStyleOptionGraphicsItem>
#include <QPointF>
#include <math.h>
#include "pit.h"
#include <QDebug>

Ball::Ball(int x, int y, int row, int col, int d, Field *field) : lastRow(row), lastCol(col), d(d), field(field)
{
    setPos(x, y);
    lastPos = pos();
    setFlag(ItemIsMovable);
}

void Ball::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget){
    painter->setBrush(QBrush(Qt::blue));
    painter->drawEllipse(boundingRect());
}

void Ball::mousePressEvent(QGraphicsSceneMouseEvent *event){
    lastPos = pos();
    QGraphicsItem::mousePressEvent(event);
}

void Ball::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    QList<QGraphicsItem*> pitList = collidingItems();
    if(pitList.size() == 1){
        Pit *pit = qgraphicsitem_cast<Pit*>(pitList[0]);
        if(pit != 0){
            if( abs(pit->pos().x() - pos().x()) < d && abs(pit->pos().y() - pos().y()) < d ){
                int row = pit->row();
                int col = pit->col();

                if(abs(lastRow - row) == 2 && abs(lastCol - col) == 0 ||
                        abs(lastRow - row) == 0 && abs(lastCol - col) == 2){

                    int r, c;
                    if(lastRow == row){
                        r = row;
                        c = (lastCol > col) ? col + 1 : col - 1;
                    }else{
                        c = col;
                        r = (lastRow > row) ? row + 1 : row - 1;
                    }
                    Pit *jumpPit = field->getPitByIndex(r, c);

                    Ball *ball = jumpPit->getBall();
                    if(ball != 0){
                        setPos(pit->pos());
                        lastRow = row;
                        lastCol = col;
                        lastPos = pos();
                        field->removeItem(ball);
                        QGraphicsItem::mouseReleaseEvent(event);
                        return;
                    }
                }
            }
        }
    }

    setPos(lastPos);
    QGraphicsItem::mouseReleaseEvent(event);
}

QPainterPath Ball::shape() const
{
    QPainterPath path;
    path.addEllipse(boundingRect());
    return path;
}

QRectF Ball::boundingRect() const{
    return QRectF(0, 0, d, d);
}
